﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;

using ABCat.Core;
using ABCat.Core.Plugins;
using ABCat.Core.Plugins.DataSets;
using ABCat.Core.Plugins.UI;
using ABCat.Shared.Properties;

using Xceed.Wpf.DataGrid;

namespace ABCat.Plugins.RecordsList.WpfToolKit
{
	[PluginCreator("Torrents list on Wpf.Toolkit.DataGrid control", WorkModeEnum.PerCall),
	UsedImplicitly]
	public partial class RecordsListWpfToolkitUc : IRecordsListPlugin
	{
		#region + Events +

		public event EventHandler Disposed;
		public event EventHandler<ItemDoubleClickRowEventArgs> ItemDoubleClick;

		#endregion
		#region + Fields +

		public readonly Context Context;

		#endregion
		#region + Properties +

		public Config Config		{get; set;}
		public FrameworkElement Control
		{
			get
			{
				return this;
			}
		}

		public IEnumerable<IAudioBook> Data
		{
			get { return (IEnumerable<IAudioBook>)grid.ItemsSource; }
			set
			{
				if (grid.ItemsSource != null) StoreLayout();
				grid.ItemsSource = value;
				RestoreLayout();
			}
		}

		public IEnumerable<IAudioBook> SelectedItems
		{
			get
			{
				return grid.SelectedItems.Cast<IAudioBook>();
			}
		}

		#endregion
		#region + Ctor +

		public RecordsListWpfToolkitUc(Context context)
		{
			InitializeComponent();
			Context = context;
			grid.MouseDoubleClick += grid_MouseDoubleClick;
		}

		#endregion
		#region + Logic +

		public bool CheckForConfig(bool correct, out Config incorrectConfig)
		{
			incorrectConfig = null;
			return true;
		}

		public void Dispose()
		{
			Disposed.Fire(this);
		}

		public void RestoreLayout()
		{
			byte[] layout;
			if (Config.TryLoadLayout("RecordsListWpfToolkutUc_grid_Layout", out layout))
			{
				SetGridColumnsLayoutFromXml(grid, Encoding.Default.GetString(layout));
			}
		}

		public void StoreLayout()
		{
			var layout = GetXmlFromGridColumnsLayout(grid);
			Config.SaveLayout("RecordsListWpfToolkutUc_grid_Layout", Encoding.Default.GetBytes(layout));
		}

		private string GetXmlFromGridColumnsLayout(DataGridControl grid)
		{
			var builder = new System.Text.StringBuilder();

			builder.Append("<grid>\r");

			foreach (Column column in grid.Columns)
			{
				if (column.Visible)
				{
					string sort;

					if (column.SortDirection == SortDirection.Ascending) sort = "Ascending";
					else if (column.SortDirection == SortDirection.Descending) sort = "Descending";
					else sort = "None";

					builder.AppendFormat("<column name='{0}' width='{1}' visibleIndex='{2}' sort='{3}' sortIndex='{4}'/>", column.FieldName, Math.Ceiling(column.Width), column.VisiblePosition, sort, column.SortIndex);

					builder.Append("\r");
				}
			}

			if (grid.Items.GroupDescriptions != null)
			{
				foreach (DataGridGroupDescription dataGridGroupDescription in grid.Items.GroupDescriptions)
				{
					builder.AppendFormat("<dataGridGroupDescription propertyName='{0}'/>", dataGridGroupDescription.PropertyName);
					builder.Append("\r");
				}
			}

			builder.Append("</grid>");

			return builder.ToString();
		}

		private void grid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			ItemDoubleClick.Fire(this, new ItemDoubleClickRowEventArgs((IAudioBook)grid.CurrentItem));
		}

		private void SetGridColumnsLayoutFromXml(DataGridControl grid, string xmlFragment)
		{
			grid.BeginInit();
			var sortedColumns = new System.Collections.SortedList();
			var sortDirections = new System.Collections.SortedList();

			var reader = new System.Xml.XmlTextReader(xmlFragment, System.Xml.XmlNodeType.Element, null);

			if (grid.Items.GroupDescriptions != null)
			{
				grid.Items.GroupDescriptions.Clear();

				while (reader.Read())
				{
					if (reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name == "column")
					{
						string str = reader.GetAttribute("name");

						var column = grid.Columns[str];

						//column.Title = str;

						if (column != null && column.Visible)
						{
							column.Width = Int32.Parse(reader.GetAttribute("width"));
							column.VisiblePosition = Int32.Parse(reader.GetAttribute("visibleIndex"));

							if (reader.GetAttribute("sort") == "Ascending" || reader.GetAttribute("sort") == "Descending")
							{
								int sortIndex = Int32.Parse(reader.GetAttribute("sortIndex"));
								sortedColumns.Add(sortIndex, column);
								sortDirections.Add(sortIndex, reader.GetAttribute("sort"));
							}
						}
					}

					if (reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name == "dataGridGroupDescription")
					{
						string str = reader.GetAttribute("propertyName");
						var gd = new DataGridGroupDescription(str);
						grid.Items.GroupDescriptions.Add(gd);
					}
				}
			}

			reader.Close();

			grid.Items.SortDescriptions.Clear();

			for (int i = 0; i < sortedColumns.Count; i++)
			{
				bool ascending = (sortDirections.GetByIndex(i).ToString() == "Ascending");
				var column = (Column)sortedColumns.GetByIndex(i);
				string str = (string)column.Title;
				if (ascending) grid.Items.SortDescriptions.Add(new SortDescription(str, ListSortDirection.Ascending));
				else grid.Items.SortDescriptions.Add(new SortDescription(str, ListSortDirection.Descending));
			}

			grid.EndInit();
		}

		#endregion
	}
}